import java.util.Scanner;

public class reverseWords {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入字符串：");
        String s = sc.nextLine();
        System.out.println(reverse(s));
    }
    public static String reverse(String s) {
        //Java语言特性
        //1、先删除多余空格（开头和结尾的空格）
        s = s.trim();
        //2、翻转整个字符串
        String str = "";
        for(int i = s.length() - 1;i >= 0;i--){
            str = str + s.charAt(i);
        }
        //2、再根据空格切割字符串
        String[] split = str.split("\\s+");
        //3、再翻转单个字符串
        for(int i = 0;i < split.length;i++){
            String string = split[i];
            StringBuilder stringBuilder = new StringBuilder(string);
            stringBuilder.reverse();
            split[i] = stringBuilder.toString();
        }
        //4、最后返回新的字符串
        String newString = "";
        for(int i = 0;i < split.length;i++) {
            String string = split[i];
            if (i != split.length - 1) {
                newString = newString + string + " ";
            }else{
                newString = newString + string;
            }
        }
        return newString;
    }
}
